package com.rederxu.request;
import java.net.HttpURLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

public class CookieStore {

	private final static String xmlName = "Cookie_Farmer_HTTPRequest";
	private final static String endWith = "_cookieDate";
	
	public static void saveCookie(List<Cookie> cookies,Context context,String url){
		SharedPreferences settings = context.getSharedPreferences(xmlName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("url", url);
		for(int i = 0 ; i < cookies.size();i++){
			Cookie cookie = cookies.get(i);
			String cookieName = cookie.getName();
			String cookieValue = cookie.getValue();
			Date date = cookie.getExpiryDate();
			editor.putString(cookieName, cookieValue);
			if(date != null && date.getTime() > System.currentTimeMillis()){
				editor.putLong(cookieName + endWith, date.getTime());
			}else{
				editor.putLong(cookieName + endWith, System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000);
			}
		}
		editor.commit();
	}
	
	public static void setCookie(Context context,HttpPost httpPost){
		String cookie = getCookies(context);
		if(cookie != null){
			httpPost.setHeader("cookie", cookie);
		}
	}
	
	public static void setCookie(Context context,HttpGet httpGet){
		String cookie = getCookies(context);
		if(cookie != null){
			httpGet.setHeader("cookie", cookie);
		}
	}
	
	public static void setCookie(Context context,HttpURLConnection httpURLConnection){
		String cookie = getCookies(context);
		if(cookie != null){
			httpURLConnection.setRequestProperty("cookie", cookie);
		}
	}
	
	public static String getCookies(Context context){
		SharedPreferences share = ((Activity) context).getSharedPreferences(xmlName,Context.MODE_PRIVATE);
		Map<String, ?> map = share.getAll();
		String cookie = null;
		for(String key : map.keySet()){
			String value = map.get(key) + "";
			if(key.endsWith(endWith)){
//				if(key.endsWith(endWith) && Long.parseLong(value) > System.currentTimeMillis()){
				if(cookie == null){
					cookie = "";
				}
				key = key.replaceAll(endWith, "");
				value = map.get(key) + "";
				cookie +=  key + "=" + value + ";";
			}
		}
		return cookie;
	}
	
	/**
	 * 得到当前寸的cookie对应的url
	 * */
	public static String getUrl(Context context){
		SharedPreferences share = ((Activity) context).getSharedPreferences(xmlName,Context.MODE_PRIVATE);
		return share.getString("url", null);
	}
	
	public static void clear(Context context){
		SharedPreferences settings = context.getSharedPreferences(xmlName, 0);
        SharedPreferences.Editor editor = settings.edit();
		editor.clear().commit();
	}
}
